package cn.jiadakeji.parent.config.security.filter;

import cn.hutool.extra.servlet.ServletUtil;
import cn.jiadakeji.parent.common.constant.HttpStatus;
import cn.jiadakeji.parent.common.core.domain.AjaxResult;
import cn.jiadakeji.parent.config.security.CustomerContext;
import cn.jiadakeji.parent.config.security.handle.PermitPathSupport;
import cn.jiadakeji.parent.dto.CustomerJwtDTO;
import cn.jiadakeji.parent.service.TokenService;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * token过滤器 验证token有效性
 * 
 * @author ruoyi
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter
{
    @Autowired
    private TokenService tokenService;
    @Autowired
    private PermitPathSupport permitPathSupport;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {

        try {
            //不需要登录的直接filter
            if(permitPathSupport.match(request.getRequestURI())){
                chain.doFilter(request, response);
                return;
            }
            CustomerJwtDTO customerJwtDTO = tokenService.getLoginUser(request);
            if (null != customerJwtDTO) {
                CustomerContext.put(customerJwtDTO);
                chain.doFilter(request, response);

             }else {
                int code = HttpStatus.UNAUTHORIZED;
                String msg = "请求访问: " + request.getRequestURI() + "，认证失败，无法访问系统资源";
                response.setCharacterEncoding("utf-8");
                response.setStatus(code);
                ServletUtil.write(response,JSON.toJSONString(AjaxResult.error(code, msg)), "application/json");
            }
        }finally {
            CustomerContext.remove();
        }


    }
}
